<?php
if (!defined('BASEPATH'))
	exit('No direct script access allowed');

class land_type extends CI_Controller {
	var $data = array();

	public function __construct() {
		parent::__construct();

		$this -> output -> cache(0);
		$this -> data['current_module'] = site_url("land_type");
		$this -> data['css_url'] = base_url() . 'css/';
		$this -> data['javscript_url'] = base_url() . 'script/';
		$this -> data['img_url'] = base_url() . 'images/';
		$this -> load -> model('color');
			$this->data['nowmenu']="land";
		$this->data['title']="Land Type";
		$this->data['role_id']=$this -> session -> userdata('role_id');
	}

	public function map($landid) {
		$query2 = $this -> db -> query('SELECT Lat,Lng,MAP_COLOR FROM land where landid=' . $landid);

		$row = $query2 -> row();
		//14.028, 100.657
		$colorPolygon = "";
		if ($query2 -> num_rows() > 0) {
			$colorPolygon = $row -> MAP_COLOR;
			$this -> data['current_lat'] = $row -> Lat;
			$this -> data['current_lng'] = $row -> Lng;
		} else {
			$colorPolygon = "00005A";
			$this -> data['current_lat'] = "14.028";
			$this -> data['current_lng'] = "100.657";
		}
		$count = 0;
		$javaScipt = "";
		$START_RED = 0;
		$START_GREEN = 0;
		$START_BLUE = 90;
		$queryPolygon = $this -> db -> query("SELECT * FROM land_polygon_map where LAND_ID=" . $landid);
		$tmpString = "var paths" . $count . " =[";
		foreach ($queryPolygon->result() as $rowPolygon) {
			$tmpString .= "new google.maps.LatLng(" . $rowPolygon -> Lat . "," . $rowPolygon -> Log . "),";
		}
		$queryPolygon -> free_result();
		$tmpString .= "];";

		// $hexColor = $this -> color -> rgb2html($START_RED, $START_GREEN, $START_BLUE);
		// $START_BLUE = $START_BLUE + 10;
		$hexColor = "#" . $colorPolygon;
		//	$hexColor="#ff0000";
		$tmpString .= "var shape" . $count . " = new google.maps.Polygon({
					paths :paths" . $count . ",
					strokeColor : '" . $hexColor . "',
					strokeOpacity : 0.8,
					strokeWeight : 2,
					fillColor : '" . $hexColor . "',
					fillOpacity : 0.35
				});
				 google.maps.event.addListener(shape" . $count . ", 'click', function() {
				 	
	
				});
				shape" . $count . ".setMap(map);";

		$javaScipt .= $tmpString;
		$this -> data['map_script'] = $javaScipt;
		$this -> load -> view('land/map', $this -> data);
	}

	public function landupload() {
		// $query2 = $this -> db -> query('SELECT Lat,Lng FROM land limit 0,1');
		// $row = $query2 -> row();
		// //14.028, 100.657
		// if ($query2 -> num_rows() > 0) {
		// $this -> data['current_lat'] = $row -> Lat;
		// $this -> data['current_lng'] = $row -> Lng;
		// } else {
		// $this -> data['current_lat'] = "14.028";
		// $this -> data['current_lng'] = "100.657";
		// }
		// $count = 0;
		// $javaScipt = "";
		// $START_RED = 0;
		// $START_GREEN = 0;
		// $START_BLUE = 90;
		// $query = $this -> db -> query("SELECT * FROM land order by landid desc");
		//
		// foreach ($query->result() as $row) {
		//
		// $queryPolygon = $this -> db -> query("SELECT * FROM landcrop_polygon_map where LAND_ID=" . $row -> landid);
		// $tmpString = "var paths" . $count . " =[";
		// foreach ($queryPolygon->result() as $rowPolygon) {
		// $tmpString .= "new google.maps.LatLng(" . $rowPolygon -> Lat . "," . $rowPolygon -> Log . "),";
		// }
		// $queryPolygon -> free_result();
		// $tmpString .= "];";
		//
		// $hexColor = $this -> color -> rgb2html($START_RED, $START_GREEN, $START_BLUE);
		// $START_BLUE = $START_BLUE + 10;
		// //	$hexColor="#ff0000";
		// $tmpString .= "var shape" . $count . " = new google.maps.Polygon({
		// paths :paths" . $count . ",
		// strokeColor : '" . $hexColor . "',
		// strokeOpacity : 0.8,
		// strokeWeight : 2,
		// fillColor : '" . $hexColor . "',
		// fillOpacity : 0.35
		// });
		// google.maps.event.addListener(shape" . $count . ", 'click', function() {
		// //var area = google.maps.geometry.spherical.computeArea(paths" . $count . ");
		// // document.getElementById('user_infor').innerHTML = '<b>Land Name:</b>" . $row -> name . "<br/><b>Latitude:</b>" . $row -> Lat . "<br/><b>Longtitude:</b>" . $row -> Lng . "<br/><b>Area Size:</b>'+area+'ตารางเมตร';
		//
		//
		// });
		// shape" . $count . ".setMap(map);";
		//
		// $javaScipt .= $tmpString;
		// $count++;
		// }

		$queryV = $this -> db -> query("SELECT  `uuid` , CONCAT(  `vfirstname` ,  '  ',  `vlastname` ) AS full_name FROM  `vendor`");
		$dataVender = array();
		$dataVender[0] = "Select";
		foreach ($queryV->result() as $row) {
			$dataVender[$row -> uuid] = $row -> full_name;
		}

		$this -> data['ownerLand'] = $dataVender;
		$query = $this -> db -> query("SELECT *  FROM  `landtype` ");
		$selectLandtype = "";
		$dataLandType = array();
		$dataLandType[0] = "Select";
		foreach ($query->result() as $row) {
			$dataLandType[$row -> landtypeid] = $row -> name;

		}
		// landtype
		$this -> data['landtype'] = $dataLandType;
		// $this -> data['map_script'] = $javaScipt;
		$this -> load -> view('admin/land/land_manage', $this -> data);
	}

	public function save_address() {
		print_r($_REQUEST);
		$data = array('housenum' => $_REQUEST['housenum'], 'village' => $_REQUEST['village'], 'moono' => $_REQUEST['moono'], 'street' => $_REQUEST['street'], 'district' => $_REQUEST['district'], 'city' => $_REQUEST['city'], 'province' => $_REQUEST['province'], 'country' => $_REQUEST['country'], 'zipcode' => $_REQUEST['zipcode']);

		$this -> db -> update('land_address', $data, "land_addressid =" . $_REQUEST['land_docid']);

		if ($_REQUEST['ownerland'] != "0") {
			$query2 = $this -> db -> query('SELECT * FROM land_owner where landid=' . $_REQUEST['landid']);
			$row = $query2 -> row();
			$data = array();
			$data['landid'] = $_REQUEST['landid'];
			$data['uuid'] = $_REQUEST['ownerland'];
			if ($query2 -> num_rows() > 0) {
				$this -> db -> update('land_owner', $data, "ID =" . $row -> ID);

			} else {
				$this -> db -> insert('land_owner', $data);
			}
		}

		//ownerLand
		// $_REQUEST['landtype']
		$this -> db -> update('land', array('landtypeid' => $_REQUEST['landtype'], 'MAP_COLOR' => $_REQUEST['color_map']), "land_addressid =" . $_REQUEST['land_docid']);

		echo "Save Complete";
	}

	public function uploadkml() {

		if (isset($_FILES["uploadfile"]["name"]) && $_FILES["uploadfile"]["name"] != "") {
			$save_tmp = time() . $_FILES["uploadfile"]["name"];
			$saveKMLPath = $_SERVER['DOCUMENT_ROOT'] . "/data/kml/" . $save_tmp;
			if (move_uploaded_file($_FILES["uploadfile"]["tmp_name"], $saveKMLPath)) {

				$data = array('land_file' => $save_tmp);
				$this -> db -> insert('land_doc', $data);
				$landDocID = $this -> db -> insert_id();

				$xml = simplexml_load_file($saveKMLPath);
				$count = 0;
				foreach ($xml->Document->Placemark as $place) {

					$checkHaveInDB = $this -> db -> query("SELECT landid FROM land where name='" . $place -> name . "'");
					$lastInsertID = "";
					$LandID = "";
					$AddressID = "";
					$count = $count + 1;
					$LandName_tm = "";
					if ($checkHaveInDB -> num_rows() > 0) {
						$row = $checkHaveInDB -> row();
						$LandID = $row -> LAND_ID;
						$this -> db -> query("delete from landcrop_polygon_map where LAND_ID=" . $LandID);
					} else {
						$data = array('name' => "" . $place -> name);
						$LandName_tm = $place -> name;
						foreach ($place->LookAt as $lookAtArea) {
							$data['Lat'] = $lookAtArea -> latitude;
							$data['Lng'] = $lookAtArea -> longitude;

						}

					}
					$dataLandAddress = array('land_docid' => $landDocID);
					$this -> db -> insert('land_address', $dataLandAddress);

					$data['land_addressid'] = $this -> db -> insert_id();
					$this -> db -> insert('land', $data);
					$LandID = $this -> db -> insert_id();
					$tmpPoligon = "";
					foreach ($place->Polygon as $areaPolygon) {

						$tmpdd = explode(",", trim($areaPolygon -> outerBoundaryIs[0] -> LinearRing -> coordinates));

						for ($i = 0; $i < count($tmpdd); $i++) {
							if ($tmpdd[$i] != "0") {

								if (($i % 2) == 0) {
									$LatLongTmp = array();
									$LatLongTmp['Log'] = str_replace("0 ", "", $tmpdd[$i]);

								} else {

									$LatLongTmp['Lat'] = str_replace("0 ", "", $tmpdd[$i]);
									$result_keyed = array_reverse($LatLongTmp, true);
									$LatLongTmp['LAND_ID'] = $LandID;
									$this -> db -> insert('landcrop_polygon_map', $LatLongTmp);

									$comma_separated = implode(" ", $result_keyed);
									$tmpPoligon .= $comma_separated . ",";
								}

							}
						}

					}
					$str = substr($tmpPoligon, 0, strlen($tmpPoligon) - 1);

					$sqlInsertPoligon = "INSERT INTO land_polygon(`name`,`polygon`) VALUES ('" . $LandName_tm . "', GeomFromText('POLYGON(( " . $str . "))'))";
					$this -> db -> query($sqlInsertPoligon);
					$polygonID = $this -> db -> insert_id();
					$calculateArea = $this -> db -> query("SELECT area(polygon) as areasize FROM  land_polygon where landcrop_polygonid=" . $polygonID);
					// $rowResultArea = $calculateArea -> row();
					//	$this->db->trans_complete();
					$this -> db -> query("update land set land_polygonid=" . $polygonID . " where landid=" . $LandID);
					// $this -> db -> update('land',  array('land_polygonid' => $polygonID),"landid=".$LandID);
					$this -> db -> update('landcrop_polygon', array('Size' => $rowResultArea -> areasize), "landcrop_polygonid =" . $polygonID);
				}
				echo $count;

			} else {
				echo "error";
			}
		}
	}

	public function getlastupload() {
		$query = $this -> db -> query("SELECT * FROM  `land` ORDER BY  `land`.`landid` asc ");

		$output = "<table width=\"100%\"  style=\"background: #FE7B09;\" >
			<tr>
				<td width=\"5%\" class=\"headerTableTopic\"  align=\"center\">ID</td>
				<td width=\"18%\" class=\"headerTableTopic\"  >LandName</td>
				<td class=\"headerTableTopic\" width=\"5%\" align=\"center\">Delete</td>
				<td class=\"headerTableTopic\" width=\"5%\" align=\"center\">Edit</td>
			</tr>";
		$imageURL = base_url() . "images/";
		if ($query -> num_rows() > 0) {
			foreach ($query->result() as $row) {
				$output .= "<tr style=\"background: #ffffff;\">";
				$output .= "<td align=\"center\">" . $row -> landid . "</td>";
				$output .= "<td>" . $row -> name . "</td>";
				$output .= "<td align=\"center\"><a href=\"javascript:deleteLand('" . $row -> landid . "')\">" . "<img src='" . $imageURL . "icon_delete.png'/></a></td>";
				$output .= "<td align=\"center\"><a href=\"javascript:getDataByID('" . $row -> landid . "','" . $row -> landtypeid . "')\">" . "<img src='" . $imageURL . "icon_edit.png'/></a></td>";
				$output .= "</tr>";
			}
		} else {
			$output .= "<tr style=\"background: #ffffff;\">";
			$output .= "<td colspan=\"4\" align=\"center\"><br />No Data<br /><br /></td>";
			$output .= "</tr>";
		}
		echo $output;
	}

	public function deleteLandArea() {
		//landtypeid	int(11)			Yes	NULL
		// land_addressid	int(11)			Yes	NULL
		// land_polygonid
		$query2 = $this -> db -> query('SELECT land_addressid,land_polygonid FROM land where landid=' . $_REQUEST['landid']);
		$row = $query2 -> row();
		$land_addressid = $row -> land_addressid;
		//	$land_polygonid = $row->land_polygonid;
		$this -> db -> delete('land', array('landid' => $_REQUEST['landid']));
		$this -> db -> delete('landcrop_polygon_map', array('LAND_ID' => $_REQUEST['landid']));
		$this -> db -> delete('land_address', array('land_addressid' => $row -> land_addressid));
		$this -> db -> delete('land_polygon', array('land_polygonid' => $row -> land_polygonid));
		$this -> db -> delete('land_polygon_map', array('LAND_ID' => $_REQUEST['landid']));

		echo "Delete Complete";
	}

	public function index() {
		$this -> load -> view('land/landtype', $this -> data);
	}

	public function getdata() {

		$query = $this -> db -> query("SELECT * FROM landtype ");

		$output = "<div class=\"table\">
						<table class=\"listing\" cellpadding=\"0\" cellspacing=\"0\">
							<tr>
								<th width=\"10%\" style=\"text-align: center;\"> ID</center></th>
								<th width=\"20%\">LandTypeName</th>
								<th>Description</th>
								<th width=\"10%\">Color</th>
								<th width=\"10%\">Delete</th>
								<th width=\"10%\">Edit</th>
						
							</tr>";

		// $output = "<table width=\"100%\"  style=\"background: #FE7B09;\" >
		// <tr>
		// <td width=\"5%\" class=\"headerTableTopic\"  align=\"center\">ID</td>
		// <td width=\"20%\" class=\"headerTableTopic\"  >LandTypeName</td>
		// <td class=\"headerTableTopic\" >Description</td>
		//
		// <td class=\"headerTableTopic\" width=\"5%\" >Delete</td>
		// <td class=\"headerTableTopic\" width=\"5%\" >Edit</td>
		// </tr>";

		//$imageURL = base_url() . "images/";

		foreach ($query->result() as $row) {
			$output .= "<tr >";
			$output .= "<td style=\"text-align: center;\">" . $row -> landtypeid . "</td>";
			$output .= "<td>" . $row -> name . "</td>";
			$output .= "<td>" . $row -> description . "</td>";
			$output .= "<td><font style='background:#" . $row -> hexcolor . ";color:#" . $row -> hexcolor . ";'>" . $row -> hexcolor . "</font></td>";
			$output .= "<td align=\"center\"><a href=\"javascript:detete('" . $row -> landtypeid . "')\"><img src='". base_url()."img/hr.gif' width=\"16\" height=\"16\" /></a></td>";
			$output .= "<td align=\"center\"><a href=\"javascript:getDataByID('" . $row -> landtypeid . "')\"><img src='".base_url()."img/edit-icon.gif' width=\"16\" height=\"16\" /></a></td>";
			$output .= "</tr>";
		}

		echo $output . "</table></div>";

	}

	//json_encode(array("name"=>"John","time"=>"2pm"));
	public function getAddressByID() {

		$query2 = $this -> db -> query('SELECT * from land_owner where landid=' . $_REQUEST['landid']);

		if ($query2 -> num_rows() > 0) {

			$query = $this -> db -> query("SELECT
			land_owner.uuid,
			land_address.land_addressid,
			land_address.housenum,
			land_address.village,
			land_address.moono,
			land_address.street,
			land_address.district,
			land_address.city,
			land_address.province,
			land_address.country,
			land_address.zipcode,
			land_address.land_docid,
			land.landtypeid,
			land.MAP_COLOR 
			FROM
			land
			INNER JOIN land_owner ON land_owner.landid = land.landid
			INNER JOIN land_address ON land_address.land_addressid = land.land_addressid  
			 where land_address.land_addressid =" . $_REQUEST['landid']);
		} else {
			$query = $this -> db -> query("SELECT
			land_address.land_addressid,
			land_address.housenum,
			land_address.village,
			land_address.moono,
			land_address.street,
			land_address.district,
			land_address.city,
			land_address.province,
			land_address.country,
			land_address.zipcode,
			land_address.land_docid,
			land.landtypeid,
			land.MAP_COLOR 
			FROM 
			land_address
			INNER JOIN land ON land_address.land_addressid = land.land_addressid   where land.landid =" . $_REQUEST['landid']);

		}
		$tmp = json_encode($query -> result_array());
		$tmp = str_replace("[", "", $tmp);
		$tmp = str_replace("]", "", $tmp);
		echo $tmp;
	}

	public function getLandInfo() {
		$query = $this -> db -> query("SELECT * FROM  `landcrop_polygon_map` where LAND_ID =" . $_REQUEST['landid']);
		$tmp = json_encode($query -> result_array());
		$tmp = str_replace("[", "", $tmp);
		$tmp = str_replace("]", "", $tmp);
		echo $tmp;

	}

	public function getdataByID() {

		$query = $this -> db -> query("SELECT * FROM landtype where landtypeid=" . $_REQUEST['landtypeid']);
		$tmp = json_encode($query -> result_array());
		$tmp = str_replace("[", "", $tmp);
		$tmp = str_replace("]", "", $tmp);
		echo $tmp;
	}

	public function delete() {
		if ($_REQUEST['landtypeid'] != "") {
			$this -> db -> delete('landtype', array('landtypeid' => $_REQUEST['landtypeid']));
		}

	}

	public function update() {

		$data = array('name' => $_REQUEST['name'], 'description' => $_REQUEST['description'], 'hexcolor' => $_REQUEST['color_map']);
		if ($_REQUEST['landtypeid'] != "0") {
			$this -> db -> update('landtype', $data, "landtypeid =" . $_REQUEST['landtypeid']);
			echo "Update Complete";
		} else {
			$this -> db -> insert('landtype', $data);
			echo "Add Complete";
		}
	}

	// public function update($Landtypeid, $LandTypeName, $LandDescription) {
	// $data = array('name' => $LandTypeName, 'description' => $LandDescription);
	// echo $_REQUEST['name'];
	// if ($Landtypeid == "0") {
	// $this -> db -> insert('landtype', $data);
	// } else {
	// $this -> db -> update('landtype', $data, "landtypeid =" . $Landtypeid);
	// }
	// }

}
?>